//
//  PAAPIAdapter.m
//  PAMobileWallet
//
//  Created by william mu on 13-9-17.
//  Copyright (c) 2013年 平安付. All rights reserved.
//

#import "PAAPIAdapter.h"
#import "OpenUDID.h"

typedef void (^ PAAPIAdtSuccessHandler)(NSDictionary *resInJSON, NSDictionary *userInfo);
typedef void (^ PAAPIAdtFailureHandler)(NSInteger errorCode, NSDictionary *userInfo);

@interface PAAPIAdapter()
@property(nonatomic, strong)PANetworkManager *networkManager;
@end

@implementation PAAPIAdapter

+ (instancetype)shared {
    static dispatch_once_t onceToken;
    static PAAPIAdapter *__apiAdapterInstance;
    dispatch_once(&onceToken, ^{
        __apiAdapterInstance = [[PAAPIAdapter alloc] init];
        
        __apiAdapterInstance.networkManager = [PANetworkManager sharedInstance];
    });
    
    return __apiAdapterInstance;
}

-(int) getUniqueID
{
    static int ID = 0;
    return ID ++;
}

-(id) init
{
    if(self = [super init])
    {
    }
    return self;
}

- (void)encryptionPassword:(NSString *)password success:(PAPublicKeyback)success error:(PANetworkErrorBlock)onError{
    NSDictionary *params = @{
                             k_operationType: @"op_query_public_key",
                             k_sessionId: @"",
                             k_clientId: [OpenUDID value],
                             };
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[@"successHandler"] = ^(NSDictionary *resInJSON, NSDictionary *userInfo)
    {
        if (success) success(resInJSON[k_resultCode], resInJSON[k_sessionId], resInJSON[k_resultMsg] , resInJSON[k_controllerPublicKey], resInJSON[k_securityPublicKey], resInJSON[k_timestamp]);
    };
    
    userInfo[@"failureHandler"] = ^(NSInteger errorCode, NSDictionary *userInfo)
    {
        NSError* error = [NSError errorWithDomain:@"" code:errorCode userInfo:userInfo];
        if (onError) onError(error);
    };
    
    
    [self.networkManager reqAsynParamDic:params userInfo:userInfo delegate:self];
}

- (void)paRequestRespons:(NSDictionary *)responsDic userInfo:(NSDictionary *)userInfo
{
    if(![userInfo objectForKey:@"successHandler"])
        return;
    
    PAAPIAdtSuccessHandler successHandler = (PAAPIAdtSuccessHandler)[userInfo objectForKey:@"successHandler"];
    
    successHandler(responsDic, userInfo);
    
}

- (void)paRequestAccurateFailed:(NSInteger)errorCode userInfo:(NSDictionary *)userInfo
{
    if(![userInfo objectForKey:@"failureHandler"])
        return;
    
    PAAPIAdtFailureHandler failureHandler = (PAAPIAdtFailureHandler)[userInfo objectForKey:@"failureHandler"];
    
    failureHandler(errorCode, userInfo);
}



@end
